const db = require('@/db/db-connection')
const { multipleColumnSet } = require('@/utils/common.util')

class UserCollectToolModel {
  constructor () {
    this.tableName = 'user_collect_tool'
  }

  /**
   * find user collect tool list
   * @param {*} param
   * @param {*} fields
   * @returns
   */
  async find (userId) {
    try {
      const sql = `SELECT t.*, tool.*

      FROM ${this.tableName} t
      
      LEFT JOIN tool ON tool.id = t.toolId

      WHERE t.userId = ?`

      const result = await db.query(sql, [userId])

      return result
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * find one user_tool collect
   * @param {*} userId
   * @param {*} toolId
   * @returns
   */
  async findOne (userId, toolId) {
    try {
      const sql = `SELECT * FROM ${this.tableName} WHERE userId = ? AND toolId = ?`

      const result = await db.query(sql, [userId, toolId])

      return result[0]
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * get user_tool collect total
   * @param {*} param
   */
  async total (param) {
    try {
      const { columnSet, values } = multipleColumnSet(param)

      const sql = `SELECT COUNT(*) as total FROM ${this.tableName} WHERE ${columnSet}`

      const total = await db.query(sql, values)

      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * add user_tool fouce map
   * @param {*} userId
   * @param {*} toolId
   */
  async add (userId, toolId) {
    try {
      const sql = `INSERT INTO ${this.tableName} (userId, toolId) VALUES (?, ?)`

      await db.query(sql, [userId, toolId])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * delete user_tool fouce map
   * @param {*} userId
   * @param {*} toolId
   */
  async delete (param) {
    try {
      const { columnSet, values } = multipleColumnSet(param, ' AND ')

      const sql = `DELETE FROM ${this.tableName} WHERE ${columnSet}`

      await db.query(sql, values)
    } catch (error) {
      throw new Error(error)
    }
  }

  async bacthDelete (folderId) {
    try {
      const sql = `DELETE FROM ${this.tableName} t WHERE t.toolId IN (SELECT s.id FROM sites s WHERE s.folderId = ?)`
      await db.query(sql, [folderId])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new UserCollectToolModel()
